from django.shortcuts import render,redirect
from django.http import HttpResponse,FileResponse
import os
from .models import *
from django.db.models import Q
import datetime
# Create your views here.

def managerfile(request):
    file1 = File.file.filter(isDelete=False).filter(Q(users__id = 1)&Q(filetypes__id = 1))
    file2 = File.file.filter(isDelete=False).filter(Q(users__id=1) & Q(filetypes__id=2))
    file3 = File.file.filter(isDelete=False).filter(Q(users__id=1) & Q(filetypes__id=3))
    file4 = File.file.filter(isDelete=False).filter(Q(users__id=1) & Q(filetypes__id=4))
    file5 = File.file.filter(isDelete=False).filter(Q(users__id=1) & Q(filetypes__id=5))
    types = Filetype.objects.all()
    type1 = types[0]
    type2 = types[1]
    type3 = types[2]
    type4 = types[3]
    type5 = types[4]
    files = {'files1':file1,'files2':file2,'files3':file3,'files4':file4,'files5':file5,
             'type1':type1, 'type2':type2, 'type3':type3, 'type4':type4, 'type5':type5,}
    return render(request, 'modfile/managerfile.html',files)

def tomanager(request, id):
    fcount = File.file.all()
    count = len(fcount)
    if int(id) > count:
        return render(request, 'modfile/error.html')
    file = File.file.get(pk = int(id))
    share = file.isShare
    filetype = Filetype.objects.filter()
    if share:
        share = '共享文件'
    else:
        share = '非共享文件'
    files = {'files': file,'share':share, 'types':filetype}
    return render(request, 'modfile/tomanager.html',files)

def managerhandler(request):
    share = request.POST.get('M_share')
    filetype = request.POST.get('M_filetype')
    types = Filetype.objects.get(pk = int(filetype))
    fileid = request.POST.get('M_id')
    file = File.file.searchid(int(fileid))
    nowtime = datetime.datetime.now().strftime('%Y-%m-%d')
    file.update(isShare = int(share), filetypes = types,changeDate = nowtime)
    return redirect('/modfile/managerfile/')

def delfile(request,fileid):
    fcount = File.file.all()
    count = len(fcount)
    if int(fileid) > count:
        return render(request, 'modfile/error.html')
    file = File.file.searchid(int(fileid))
    file.update(isDelete = True)
    return redirect('/modfile/managerfile/')

def delall(request):
    filelist = request.POST.getlist('M_check1')
    filelist += request.POST.getlist('M_check2')
    filelist += request.POST.getlist('M_check3')
    filelist += request.POST.getlist('M_check4')
    filelist += request.POST.getlist('M_check5')
    for fileid in filelist:
        file = File.file.searchid(int(fileid))
        file.update(isDelete = True)
    return redirect('/modfile/managerfile/')

def loadfile(request):
    filetypes = Filetype.objects.filter()
    types = {'type': filetypes,'success':''}
    return render(request, 'modfile/loadfile.html', types)

def loadhandler(request):
    files = request.FILES.get('M_myfile')#前端传入的文件
    # #在static 路径下 以二进制写的方式打开一个新的文件，文件名是前端传入的文件名
    #
    # exist = File.file.searchfile(files.name)
    # if len(exist) > 0:
    #     context = {'success': '上传失败，文件已存在！'}
    #     return render(request, 'modfile/loadfile.html', context)
    file = open(os.path.join('static', 'modfile', 'file', files.name), 'wb')
    #将前端文件的内容写入static的文件里
    for fp in files.chunks():
        file.write(fp)
    file.close()
    isshare = request.POST.get('M_isshare')
    filetype = request.POST.get('M_filetype')
    # f = File()
    # f.fileName = files.name
    filePath = os.path.join('static', 'modfile', 'file', files.name)
    isshare = int(isshare)
    filetype = Filetype.objects.get(pk = int(filetype))
    # f.filetypes = filetype#Filetype.objects.get(pk = int(filetype))
    user = User.objects.get(pk = 1)
    # f.users = user#User.objects.get(pk = 1)
    # f.save()
    f = File.file.createfile(files.name, filePath, isshare, filetype, user)
    filetypes = Filetype.objects.filter()
    context = {'success':'上传成功！', 'type': filetypes}
    return render(request, 'modfile/loadfile.html', context)

def searchfile(request):
    file = File.file.listfile()
    file = file[0:10]
    filelist = {'files':file}
    return render(request, 'modfile/searchfile.html', filelist)

def searchhandler(request):
    searchname = request.POST.get('M_searchname')
    file = File.file.searchfile(searchname)
    filelist = {'files':file}
    return render(request, 'modfile/searchfile.html', filelist)

def preview(request, fileid):
    fcount = File.file.all()
    count = len(fcount)
    if int(fileid) > count:
        return render(request, 'modfile/error.html')
    file = File.file.searchid(int(fileid))
    filepath = file[0].filePath
    filepath = str(filepath)
    fopen = open(filepath,'rb')
    context = fopen.readlines()
    context = context[0]
    f = {'file':file,'con':context}
    return render(request, 'modfile/preview.html', f)

def download(request, id):
    fcount = File.file.all()
    count = len(fcount)
    if int(id) > count:
        return render(request, 'modfile/error.html')
    files = File.file.get(pk = int(id))
    filename = files.fileName
    filepath = files.filePath
    filepath = str(filepath)
    file = open(filepath, 'rb')
    response = FileResponse(file)
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename='+ filename +''
    return response